package me.zklh.transaction.south.adapter.repository;

import me.zklh.transaction.domain.entity.Account;
import me.zklh.transaction.south.adapter.repository.builder.AccountBuilder;
import me.zklh.transaction.south.adapter.repository.dao.AccountDAO;
import me.zklh.transaction.south.adapter.repository.dao.AccountDO;
import me.zklh.transaction.south.port.repository.AccountRepository;

import javax.annotation.Resource;

public class AccountRepositoryImpl implements AccountRepository {
    @Resource
    private AccountDAO accountDAO;

    @Resource
    public AccountBuilder accountBuilder;

    @Override
    public Account find(Long id) {
        AccountDO accountDO = accountDAO.selectById(id);
        return accountBuilder.toAccount(accountDO);
    }

    @Override
    public Account find(String accountNumber) {
        AccountDO accountDO = accountDAO.selectByAccountNumber(accountNumber);
        return accountBuilder.toAccount(accountDO);
    }

    @Override
    public Account findByUserId(Long userId) {
        AccountDO accountDO = accountDAO.selectByUserId(userId);
        return accountBuilder.toAccount(accountDO);
    }

    @Override
    public Account save(Account account) {
        AccountDO accountDO = accountBuilder.fromAccount(account);
        if (accountDO.getId() == null) {
            accountDAO.insert(accountDO);
        } else {
            accountDAO.update(accountDO);
        }
        return accountBuilder.toAccount(accountDO);
    }

}
